package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"video-manage-sys/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	likeCount, _ := strconv.Atoi(c.PostForm("like_count"))
	movie := models.Movie{
		Title:     title,
		Content:   content,
		Img:       img,
		LikeCount: likeCount,
		UserID:    userId,
	}
	err := models.DB.Preload("User").Create(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.Movie{}).Count(&count)
	var movie []models.Movie
	err := models.DB.Preload("User").Order("like_count").Offset(offset).Limit(size).Find(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"movie": movie,
		},
	})
	return

}
